package com.shouhuobao.samecity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.InputFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.model.SameCityHistoryBean;
import com.collectplus.express.model.SameCityParcelBean;
import com.collectplus.express.tools.ContactUtils;
import com.collectplus.express.tools.LengthInputFilter;
import com.collectplus.express.tools.TextWatcherExt;

import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * Created by joker on 2017/12/27.
 * 收件人信息或寄件人信息确认界面
 */
public class SameCityInfoConfirmActivity extends BaseActivity2 implements View.OnClickListener {

    private TextView mBuildNameTV;//建筑物名称
    private EditText mAddressTV;//详细地址
    private EditText mNameET;//姓名
    private EditText mPhoneET;//手机号
    private Button mButton;//确认按钮

    private int type;// 0 寄件人信息  1 收件人信息
    private int loadType = 0;// 0 从缓存中读取  1 从静态变量中获取
    /**
     * 是否从{@link SameCityFormActivity} 进入的
     * true 是  false 否
     * 如果从首页进来的，直接从内存中取数据并加载
     */
    private boolean isFromSameCityForm = false;
    private SameCityHistoryBean item = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        type = getIntent().getIntExtra("type", 0);
        loadType = getIntent().getIntExtra("loadType", 0);
        isFromSameCityForm = getIntent().getBooleanExtra("isFrom", false);
        item = (SameCityHistoryBean) getIntent().getSerializableExtra("item");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_samecity_confirm_info);
        super.findViewById();
        if (type == 1) {
            getAppTitle().setCommonTitle("收件人信息");
        } else {
            getAppTitle().setCommonTitle("寄件人信息");
        }
        mBuildNameTV = (TextView) findViewById(R.id.build_name_tv);
        mBuildNameTV.setOnClickListener(this);
        findViewById(R.id.receiver_contact).setOnClickListener(this);
        mAddressTV = (EditText) findViewById(R.id.address_et);
        mNameET = (EditText) findViewById(R.id.name_et);
        mPhoneET = (EditText) findViewById(R.id.phone_et);
        mButton = (Button) findViewById(R.id.confirm_bt);
        mButton.setOnClickListener(this);

        mNameET.addTextChangedListener(textWatcher);
        mPhoneET.addTextChangedListener(textWatcher);
        mAddressTV.addTextChangedListener(textWatcher);
        mPhoneET.setFilters(new InputFilter[]{new InputFilterExt(1),//
                new LengthInputFilter(mPhoneET, 11).setInputCallback(inputCallback)});
        mNameET.setFilters(new InputFilter[]{new InputFilterExt(0), new LengthInputFilter(mNameET, 10).setInputCallback(inputCallback)});
        mAddressTV.setFilters(new InputFilter[]{new InputFilterExt(0), new LengthInputFilter(mAddressTV, 50).setInputCallback(inputCallback)});
        loadDataToView();
    }

    private void loadDataToView() {
        SameCityParcelBean bean = AppCache.getSameCityParcelBean();
        if (bean != null) {
            try {
                mNameET.setText("");
                mAddressTV.setText("");
                mPhoneET.setText("");
                if (item == null) {
                    if (isFromSameCityForm) {
                        //收件人信息
                        if (type == 1) {
                            ((TextView) findViewById(R.id.name_title_tv)).setText("收件姓名：");
                            mBuildNameTV.setText(bean.getReceiveBuildName());
                            mAddressTV.setText(Str.filter(bean.getReceiveAddressDesc()));
                            if (isNotEmpty(bean.getReceiveName())) {
                                mNameET.setText(Str.filter(bean.getReceiveName()));
                                mNameET.setSelection(mNameET.getText().toString().length());
                            }
                            if (isNotEmpty(bean.getReceivePhone())) {
                                mPhoneET.setText(bean.getReceivePhone());
                            }
                        } else {
                            ((TextView) findViewById(R.id.name_title_tv)).setText("寄件姓名：");
                            mBuildNameTV.setText(bean.getSendBuildName());
                            mAddressTV.setText(Str.filter(bean.getSendAddressDesc()));
                            if (isNotEmpty(bean.getSendName())) {
                                mNameET.setText(Str.filter(bean.getSendName()));
                                mNameET.setSelection(mNameET.getText().toString().length());
                            }
                            if (isNotEmpty(bean.getSendPhone())) {
                                mPhoneET.setText(bean.getSendPhone());
                            }
                        }
                    }
                } else {
                    if (isFromSameCityForm) {
                        //收件人信息
                        if (type == 1) {
                            ((TextView) findViewById(R.id.name_title_tv)).setText("收件姓名：");
                            mBuildNameTV.setText(item.getBuildName());
                            mAddressTV.setText(Str.filter(item.getAddressDesc()));
                            if (isNotEmpty(bean.getReceiveName())) {
                                mNameET.setText(Str.filter(bean.getReceiveName()));
                                mNameET.setSelection(mNameET.getText().toString().length());
                            }
                            if (isNotEmpty(bean.getReceivePhone())) {
                                mPhoneET.setText(bean.getReceivePhone());
                            }
                        } else {
                            ((TextView) findViewById(R.id.name_title_tv)).setText("寄件姓名：");
                            mBuildNameTV.setText(item.getBuildName());
                            mAddressTV.setText(Str.filter(item.getAddressDesc()));
                            if (isNotEmpty(bean.getSendName())) {
                                mNameET.setText(Str.filter(bean.getSendName()));
                                mNameET.setSelection(mNameET.getText().toString().length());
                            }
                            if (isNotEmpty(bean.getSendPhone())) {
                                mPhoneET.setText(bean.getSendPhone());
                            }
                        }
                    } else {
                        //确认界面返回再次进入
                        //只有寄件人选择的信息才在静态变量中获取
                        if (loadType == 1 && type == 0) {
                            mBuildNameTV.setText(item.getBuildName());
                            if (isNotEmpty(SameCityAddressActivity.address)) {
                                mAddressTV.setText(Str.filter(SameCityAddressActivity.address));
                            }
                            if (isNotEmpty(SameCityAddressActivity.name)) {
                                mNameET.setText(Str.filter(SameCityAddressActivity.name));
                            }
                            if (isNotEmpty(SameCityAddressActivity.phone)) {
                                mPhoneET.setText(SameCityAddressActivity.phone);
                            }
                        } else {
                            mBuildNameTV.setText(item.getBuildName());
                            //收件人信息
                            if (type == 1) {
                                ((TextView) findViewById(R.id.name_title_tv)).setText("收件姓名：");
                                if (isNotEmpty(bean.getReceiveAddress())) {
                                    mAddressTV.setText(Str.filter(bean.getReceiveAddressDesc()));
                                } else {
                                    mAddressTV.setText(Str.filter(item.getAddressDesc()));
                                }
                                if (isNotEmpty(bean.getReceiveName())) {
                                    mNameET.setText(Str.filter(bean.getReceiveName()));
                                    mNameET.setSelection(mNameET.getText().toString().length());
                                }
                                if (isNotEmpty(bean.getReceivePhone())) {
                                    mPhoneET.setText(bean.getReceivePhone());
                                }
                            } else {
                                ((TextView) findViewById(R.id.name_title_tv)).setText("寄件姓名：");
                                if (isEmpty(SameCityAddressActivity.address) && isEmpty(SameCityAddressActivity.name) && isEmpty(SameCityAddressActivity.phone)) {
                                    if (isNotEmpty(bean.getSendAddress())) {
                                        mAddressTV.setText(Str.filter(bean.getSendAddressDesc()));
                                    } else {
                                        mAddressTV.setText(item.getAddressDesc());
                                    }
                                    if (isNotEmpty(bean.getSendName())) {
                                        mNameET.setText(Str.filter(bean.getSendName()));
                                        mNameET.setSelection(mNameET.getText().toString().length());
                                    }
                                    if (isNotEmpty(bean.getSendPhone())) {
                                        mPhoneET.setText(bean.getSendPhone());
                                        mPhoneET.setSelection(mPhoneET.getText().toString().length());
                                    }
                                } else {
                                    if (isNotEmpty(SameCityAddressActivity.address)) {
                                        mAddressTV.setText(Str.filter(SameCityAddressActivity.address));
                                    }
                                    if (isNotEmpty(SameCityAddressActivity.name)) {
                                        mNameET.setText(Str.filter(SameCityAddressActivity.name));
                                    }
                                    if (isNotEmpty(SameCityAddressActivity.phone)) {
                                        mPhoneET.setText(SameCityAddressActivity.phone);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 输入文字的时候会调用该方法
     */
    private LengthInputFilter.InputCallback inputCallback = new LengthInputFilter.InputCallback() {

        @Override
        public void onCallback(EditText editText) {
            if (editText == mNameET && mNameET.length() > 10) {
                showToast("最多只能输入10个字哦");
            }
            if (editText == mPhoneET && mPhoneET.length() > 11) {
                showToast("最多只能输入11个数字哦");
            }
            if (editText == mAddressTV && mAddressTV.length() > 50) {
                showToast("最多只能输入50个字哦");
            }
        }
    };
    private TextWatcherExt textWatcher = new TextWatcherExt() {
        public void afterTextChanged(Editable s) {
            if (mNameET.getText().toString().trim().length() > 0 && mPhoneET.getText().toString().trim().length() > 0 //
                    && mAddressTV.getText().toString().trim().length() > 0) {
                setButtonEnableStyle(mButton, true);
            } else {
                setButtonEnableStyle(mButton, false);
            }
        }
    };

    @Override
    public void onClick(View v) {
        Intent intent = null;
        SameCityParcelBean bean = AppCache.getSameCityParcelBean();
        if (bean == null) {
            bean = new SameCityParcelBean();
            AppCache.setSameCityParcelBean(bean);
        }
        switch (v.getId()) {
            // 从通讯录中添加
            case R.id.receiver_contact:
                intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1002);
                break;
            //进行附近建筑物搜索
            case R.id.build_name_tv:
                if (type == 1) {
                    if (isFromSameCityForm) {
                        intent = new Intent(getContext(), SameCityReceiverAddressActivity.class);
                        intent.putExtra("isFrom", isFromSameCityForm);
                        startActivityForResult(intent, 1205);
                    }
                } else {
                    if (isFromSameCityForm) {
                        intent = new Intent(getContext(), SameCityAddressActivity.class);
                        intent.putExtra("isFrom", isFromSameCityForm);
                        startActivityForResult(intent, 1205);
                    } else {
                        SameCityAddressActivity.address = mAddressTV.getText().toString();
                        SameCityAddressActivity.phone = mPhoneET.getText().toString();
                        SameCityAddressActivity.name = mNameET.getText().toString();
                        finish();
                    }
                }
                break;
            //确认提交信息
            case R.id.confirm_bt:
                String name = Str.filter(mNameET.getText().toString());
                String phone = mPhoneET.getText().toString();
                String address = mAddressTV.getText().toString();
                if (isEmpty(name)) {
                    showToast("请填写姓名");
                    return;
                }
                if (name.length() > 10) {
                    showToast("姓名最多可输入10个字");
                    return;
                }
                if (isEmpty(phone)) {
                    showToast("请填写电话");
                    return;
                }
                if (phone.length() > 11) {
                    showToast("手机号最多可输入11个字");
                    return;
                }
                if (isEmpty(address)) {
                    showToast("请填写楼层门牌号");
                    return;
                }
                if (address.length() > 50) {
                    showToast("楼层门牌号最多而输入50个字");
                    return;
                }
                //收件人信息
                if (type == 1) {
                    bean.setReceiveBuildName(mBuildNameTV.getText().toString());
                    bean.setReceiveAddressDesc(Str.filter(mAddressTV.getText().toString()));
                    bean.setReceiveName(Str.filter(mNameET.getText().toString()));
                    bean.setReceivePhone(mPhoneET.getText().toString());
                    if (item != null) {
                        bean.setReceiveAddress(item.getAddress());
                        bean.setReceiveLatitude(item.getLatitude());
                        bean.setReceiveLongitude(item.getLongitude());
                        bean.setReceiveProvince(item.getProvince());
                        bean.setReceiveCity(item.getCity());
                        bean.setReceiveDistrict(item.getDistrict());
                    }
                } else {
                    bean.setSendBuildName(mBuildNameTV.getText().toString());
                    bean.setSendAddressDesc(Str.filter(mAddressTV.getText().toString()));
                    bean.setSendName(Str.filter(mNameET.getText().toString()));
                    bean.setSendPhone(mPhoneET.getText().toString());
                    if (item != null) {
                        bean.setSendAddress(item.getAddress());
                        bean.setSendLatitude(item.getLatitude());
                        bean.setSendLongitude(item.getLongitude());
                        bean.setSendProvince(item.getProvince());
                        bean.setSendCity(item.getCity());
                        bean.setSendDistrict(item.getDistrict());
                    }
                }
                AppCache.setSameCityParcelBean(bean);
                setResult(Activity.RESULT_OK);
                finish();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 手机通讯录
        if (resultCode == Activity.RESULT_OK && requestCode == 1002) {
            if (data == null) {
                return;
            }
            try {
                String[] phones = new ContactUtils().getContactPhone(getContext(), data.getData());
                mNameET.setText(phones[0]);
                mPhoneET.setText(phones[1]);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("获取联系人失败");
            }
        }
        //从选择位置界面返回
        else if (resultCode == Activity.RESULT_OK && requestCode == 1205) {
            if (data != null) {
                boolean isFinish = data.getBooleanExtra("finish", false);
                if (isFinish) {
                    setResult(Activity.RESULT_OK);
                    finish();
                } else {
                    item = (SameCityHistoryBean) data.getSerializableExtra("item");
                    loadDataToView();
                }
            } else {

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
